<!DOCTYPE html>
<html lang="en">
<head>
  <title>Vertx-Sync - Vert.x</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Vert.x is a tool-kit for building reactive applications on the JVM." name="description">
  <link href="http://vertx.io/stylesheets/docs.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/stylesheets/font-awesome.min.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/javascripts/styles/rainbow.min.css" media="screen" rel="stylesheet">
  <!-- IE 6-8 support of HTML 5 elements -->
  <!--[if lt IE 9]>
  <script src="http://static.jboss.org/theme/js/libs/html5/pre3.6/html5.min.js"></script>
  <![endif]-->

  <link rel="apple-touch-icon" sizes="57x57" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="http://vertx.io/assets/favicons/vertx-favicon-7/manifest.json">
  <link rel="mask-icon" href="http://vertx.io/assets/favicons/vertx-favicon-7/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#7d3194">
  <meta name="msapplication-TileImage" content="http://vertx.io/assets/favicons/vertx-favicon-7/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link href="http://fonts.googleapis.com/css?family=Ubuntu:400,500,700,400italic" rel="stylesheet" type="text/css">
  <link rel="alternate" type="application/rss+xml" title="RSS"
     href="http://vertx.io/feed.xml">
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-30144458-1', 'auto');
    ga('create', 'UA-71153120-1', 'auto', 'tracker');
    ga('send', 'pageview');
    ga('tracker.send', 'pageview');
  </script>
</head>
<body>

<a href="http://www.reactivemanifesto.org/" id="reactive-manifesto-banner">
  <img style="border: 0; position: fixed; right: 0; top:0; z-index: 9000"
    src="http://d379ifj7s9wntv.cloudfront.net/reactivemanifesto/images/ribbons/we-are-reactive-black-right.png">
</a>

<a id="skippy" class="sr-only sr-only-focusable" href="#content"><div class="container"><span class="skiplink-text">Skip to main content</span></div></a>

<header class="navbar navbar-default navbar-static-top" id="top" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#vertx-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="http://vertx.io/" class="navbar-brand"><img alt="Brand" src="http://vertx.io/assets/logo-sm.png"></a>
    </div>
    <nav class="collapse navbar-collapse" id="vertx-navbar-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="http://vertx.io/download/">Download</a></li>
        <li><a href="http://vertx.io/docs/">Documentation</a></li>
        <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
        <li><a href="http://vertx.io/community/">Community</a></li>
        <li><a href="http://vertx.io/materials/">Materials</a></li>
        <li><a href="http://vertx.io/blog/">Blog</a></li>        
      </ul>
    </nav>
  </div>
</header>



  <div class="page-header" id="content">
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <h1>Vertx-Sync</h1>
          
        </div>
      </div>
    </div>
  </div>




<div id="content">
  <div class="container docs-content">
    <div class="row">
      <div class="col-sm-12 col-md-push-9 col-md-3 hidden-xs hidden-sm">
        <div id="sidebar" data-spy="affix">
          <ul class="sectlevel1">
<li><a href="#_introduction">Introduction</a></li>
<li><a href="#_syncverticle">SyncVerticle</a></li>
<li><a href="#_instrumentation">Instrumentation</a></li>
<li><a href="#_getting_one_shot_async_results">Getting one-shot async results</a></li>
<li><a href="#_getting_one_shot_events">Getting one-shot events</a></li>
<li><a href="#_streams_of_events">Streams of events</a></li>
<li><a href="#_using_a_code_fiberhandler_code">Using a <code>FiberHandler</code></a></li>
<li><a href="#_further_examples">Further examples</a></li>
</ul>
        </div>
      </div>
      <div class="col-sm-12 col-md-pull-3 col-md-9">
        <div class="toc hidden-md hidden-lg">
          <h2>Table of Contents</h2>
          <ul class="sectlevel1">
<li><a href="#_introduction">Introduction</a></li>
<li><a href="#_syncverticle">SyncVerticle</a></li>
<li><a href="#_instrumentation">Instrumentation</a></li>
<li><a href="#_getting_one_shot_async_results">Getting one-shot async results</a></li>
<li><a href="#_getting_one_shot_events">Getting one-shot events</a></li>
<li><a href="#_streams_of_events">Streams of events</a></li>
<li><a href="#_using_a_code_fiberhandler_code">Using a <code>FiberHandler</code></a></li>
<li><a href="#_further_examples">Further examples</a></li>
</ul>
        </div>
        <div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Vertx-sync is a set of utilities that allow you to perform asynchronous operations and receive events in a
synchronous way, but without blocking kernel threads.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_introduction">Introduction</h2>
<div class="sectionbody">
<div class="paragraph">
<p>One of the key advantages of Vert.x over many legacy application platforms is that it is almost entirely non-blocking
(of kernel threads) - this allows it to handle a lot of concurrency (e.g. handle many connections, or messages) using
a very small number of kernel threads, which allows it to scale very well.</p>
</div>
<div class="paragraph">
<p>The non blocking nature of Vert.x leads to asynchronous APIs. Asynchronous APIs can take various forms including
callback style, promises or Rx-style. Vert.x uses callback style in most places (although it also supports Rx).</p>
</div>
<div class="paragraph">
<p>In some cases, programming using asynchronous APIs can be more challenging than using a direct synchronous style, in
particular if you have several operations that you want to do in sequence. Also error propagation is often more complex
when using asynchronous APIs.</p>
</div>
<div class="paragraph">
<p>Vertx-sync allows you to work with asynchronous APIs, but using a direct synchronous style that you&#8217;re already
familiar with.</p>
</div>
<div class="paragraph">
<p>It does this by using <code>fibers</code>. Fibers are very lightweight threads that do not correspond to underlying kernel threads.
When they are blocked they do not block a kernel thread.</p>
</div>
<div class="paragraph">
<p>Vert-sync uses <a href="http://docs.paralleluniverse.co/quasar/">Quasar</a> to implement the fibers.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Vert-sync currently only works with Java.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_syncverticle">SyncVerticle</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In order to use vertx-sync you must deploy your code as instances of <code>io.vertx.ext.sync.SyncVerticle</code>.
You should override the <code>start()</code> and (optionally) the <code>stop()</code> methods of the verticle.</p>
</div>
<div class="paragraph">
<p>Those methods <strong>must</strong> be annotated with the <code>@Suspendable</code> annotation.</p>
</div>
<div class="paragraph">
<p>Once you&#8217;ve written your sync verticle(s) you deploy them in exactly the same way as any other verticle.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_instrumentation">Instrumentation</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Vert.x uses Quasar which implements fibers by using bytecode instrumentation. This is done at run-time using a java
agent.</p>
</div>
<div class="paragraph">
<p>In order for this to work you must start the JVM specifying the java agent jar which is located in the quasar-core
jar.</p>
</div>
<div class="paragraph">
<p>TODO how to reference quasar core jar in fatjar?</p>
</div>
<div class="listingblock">
<div class="content">
<pre>-javaagent:/path/to/quasar/core/quasar-core.jar</pre>
</div>
</div>
<div class="paragraph">
<p>If you are using the <code>vertx</code> command line tools, the agent configuration can be enabled by setting the <code>ENABLE_VERTX_SYNC_AGENT</code>
environment variable to <code>true</code>, before executing <code>vertx</code>.</p>
</div>
<div class="paragraph">
<p>You can also use a offline instrumentation as with the <a href="https://github.com/vy/quasar-maven-plugin">quasar-maven-plugin</a>.
Check the <a href="http://docs.paralleluniverse.co/quasar/">Quasar documentation</a> for more details.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_getting_one_shot_async_results">Getting one-shot async results</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Many async operations in Vert.x-land take a <code>Handler&lt;AsyncResult&lt;T&gt;&gt;</code> as the last argument. An example would
executing a find using the Vert.x Mongo client or sending an event bus message and getting a reply.</p>
</div>
<div class="paragraph">
<p>Vertx-sync allows you to get the result of a one-shot asynchronous operation in a synchronous way.</p>
</div>
<div class="paragraph">
<p>This is done by using the <code><a href="../../apidocs/io/vertx/ext/sync/Sync.html#awaitResult-java.util.function.Consumer-">Sync.awaitResult</a></code> method.</p>
</div>
<div class="paragraph">
<p>The method is executed specifying the asynchronous operation that you want to execute in the form of a <code><a href="../../apidocs/java/util/function/Consumer.html">Consumer</a></code>,
the consumer is passed the handler at run-time.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">EventBus eb = vertx.eventBus();

// Send a message and get the reply synchronously

Message&lt;String&gt; reply = awaitResult(h -&gt; eb.send("someaddress", "ping", h));

System.out.println("Received reply " + reply.body());</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example the fiber is blocked until the reply is returned but no kernel thread is blocked.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_getting_one_shot_events">Getting one-shot events</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Vertx-sync can be used to get one-shot events in a synchronous way, for example firings of timers, or the executing of
an end handler. This is achieved using the <code><a href="../../apidocs/io/vertx/ext/sync/Sync.html#awaitEvent-java.util.function.Consumer-">Sync.awaitEvent</a></code> method.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">long tid = awaitEvent(h -&gt; vertx.setTimer(1000, h));

System.out.println("Timer has now fired");</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_streams_of_events">Streams of events</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In many places in Vert.x streams of events are provided by passing them to handlers.</p>
</div>
<div class="paragraph">
<p>Examples include event bus message consumers and HTTP server requests on an HTTP server.</p>
</div>
<div class="paragraph">
<p>Vert-sync allows you to receive events from such streams in a synchronous way.</p>
</div>
<div class="paragraph">
<p>You do this with an instance of <code><a href="../../apidocs/io/vertx/ext/sync/HandlerReceiverAdaptor.html">HandlerReceiverAdaptor</a></code> which implements both
<code><a href="../../apidocs/io/vertx/core/Handler.html">Handler</a></code> and <code><a href="../../apidocs/io/vertx/ext/sync/Receiver.html">Receiver</a></code>. You create an instance using
<code><a href="../../apidocs/io/vertx/ext/sync/Sync.html#streamAdaptor--">Sync.streamAdaptor</a></code>.</p>
</div>
<div class="paragraph">
<p>You can set it as a normal handler and then use the methods on <code><a href="../../apidocs/io/vertx/ext/sync/Receiver.html">Receiver</a></code> to receive
events synchronously.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example using an event bus message consumer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">EventBus eb = vertx.eventBus();

HandlerReceiverAdaptor&lt;Message&lt;String&gt;&gt; adaptor = streamAdaptor();

eb.&lt;String&gt;consumer("some-address").handler(adaptor);

// Receive 10 messages from the consumer:
for (int i = 0; i &lt; 10; i++) {

  Message&lt;String&gt; received1 = adaptor.receive();

  System.out.println("got message: " + received1.body());

}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_using_a_code_fiberhandler_code">Using a <code>FiberHandler</code></h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you want to do use fibers in a normal handler, e.g. in the request handler of an Http Server then you must first
convert the normal handler to a fiber handler.</p>
</div>
<div class="paragraph">
<p>The fiber handler runs the normal handler on a fiber.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">EventBus eb = vertx.eventBus();

vertx.createHttpServer().requestHandler(fiberHandler(req -&gt; {

  // Send a message to address and wait for a reply
  Message&lt;String&gt; reply = awaitResult(h -&gt; eb.send("some-address", "blah", h));

  System.out.println("Got reply: " + reply.body());

  // Now end the response
  req.response().end("blah");

})).listen(8080, "localhost");</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_further_examples">Further examples</h2>
<div class="sectionbody">
<div class="paragraph">
<p>There are a set of working examples demonstrating vertx-sync in action in the
<a href="https://github.com/vert-x3/vertx-examples/tree/master/sync-examples">examples repository</a></p>
</div>
</div>
</div>

        

        
          <div id="footer">
            <div id="footer-text">
              
                Last updated 2016-09-12 08:38:04 CEST
              
              
            </div>
          </div>
        
      </div>
    </div>
  </div>
</div>

<footer>
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Vert.x</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/">Home</a></li>
          <li><a href="http://vertx.io/download/">Download</a></li>
          <li><a href="http://vertx.io/docs/">Documentation</a></li>
          <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
          <li><a href="http://vertx.io/blog/">Blog</a></li>
          <li><a href="http://vertx.io/vertx2/" class="vertx-2-link">Vert.x 2</a></li>
        </ul>
      </div>
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Community</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/community/">Help &amp; Contributors</a></li>
          <li><a href="http://vertx.io/materials/">Learning materials</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx">User Group</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx-dev">Developer Group</a></li>
        </ul>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-offset-2 col-md-6 copyright">
        <p>Vert.x is open source and dual licensed under the <a href="https://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License 1.0</a> and <a href="https://www.apache.org/licenses/LICENSE-2.0.html">Apache License 2.0</a>.</p>
        <p>This website is licensed under the <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0 License</a>.<br>
        Design by <a href="http://www.michel-kraemer.com">Michel Kr&auml;mer</a>. <a href="http://www.entypo.com">Entypo pictograms</a> by Daniel Bruce.</p>
        <div class="row">
          <div class="col-xs-12 col-lg-offset-1 col-md-5">
            <a href="http://eclipse.org">
            <img class="logo eclipse-logo" src="http://vertx.io/assets/eclipse_logo_grey_small.png" width="204" height="48">
            </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-0 col-md-5">
            <a href="http://cloudbees.com">
            <img class="logo cloudbees-logo" src="http://vertx.io/assets/Button-Built-on-CB-1-grey.png" width="180" height="48">
           </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-1 col-md-5 jprofiler">
            <a href="http://www.ej-technologies.com/products/jprofiler/overview.html"
            style="text-decoration:none">
            <img class="logo jprofiler-logo" src="http://vertx.io/assets/jprofiler-logo.png" width="48" height="48"><span class="jprofiler-logo">&nbsp; JPROFILER</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>

<script src="http://static.jboss.org/theme/js/libs/jquery/jquery-1.9.1.min.js"></script>
<script src="http://vertx.io/javascripts/bootstrap.min.js"></script>
<script src="http://vertx.io/javascripts/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>



<script src="http://vertx.io/javascripts/sidebar.js"></script>


</body>
</html>
